import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_web_page/common_web_page.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/login/login_index/login_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_const.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_net_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_windows_delegate.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../app_main.dart';

/// 设置页面
class AppSettingsPage extends StatefulWidget{

  ///路由名称
  static const String ROUTER = "AppSettingsPage";

  const AppSettingsPage({Key key})
      : super(key: key);

  @override
  _AppSettingsPageState createState() => _AppSettingsPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      AppSettingsPage(),
      routeName: AppSettingsPage.ROUTER,
    );
  }
}

class _AppSettingsPageState extends BaseState<AppSettingsPage> {
  String versionName;
  LoginViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = LoginViewModel(this);
    _getPackageInfo();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _getPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      versionName = packageInfo?.version;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toInfoWidget(),
    );
  }

  Widget _toInfoWidget(){
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        _toVersionInfoWidget(),
        _toPrivacyWidget(),
        SizedBox(height: 10,),
        _toLogoutWidget(),
        Spacer(),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: ()async{
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: "此操作将永久注销您的账号，且不可登录，注销后我们会删除您的数据，请谨慎选择，是否确认？",
                cancelText: "取消",
                confirmText: "确认",
                confirmBgColor: ThemeRepository.getInstance()
                    .getMinorRedColor_F95355());
            if (result ?? false) {
              _viewModel.userLogOff(context, (){
                Future.delayed(Duration(milliseconds: 0), () async {
                  await UserRepository.getInstance().clearUserInfo();
                  RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,
                      rootNavigator: false);
                  VgToastUtils.toast(AppMain.context, "退出成功");
                });
              });

            }
          },
          child: Container(
            padding: EdgeInsets.all(40),
            alignment: Alignment.center,
            child: Text(
              "注销账号",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                  fontSize: 14
              ),
            ),
          ),
        ),
        SizedBox(
          height: NAV_HEIGHT,
        ),
      ],
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: "设置",
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  Widget _toVersionInfoWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        UpgradeRepository.getInstance(
            VgNetDelegate.of(true), VgWindowsDelegate.of(),
            onUpgradeErrorChanged: (UpgradeError error) {
              if(StringUtils.isEmpty(error?.message)){
                if(!(error.message.contains("获取升级详情失败"))){
                  VgToastUtils.toast(AppMain.context, error?.message);
                }
              }
            }).httpCheckUpgrade();
      },
      child: Container(
        height: 50,
        alignment: Alignment.centerLeft,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Text(
              "版本号",
              style: TextStyle(
                  fontSize: 15,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7()
              ),
            ),
            Spacer(),
            Text(
              versionName ?? "",
              style: TextStyle(
                  fontSize: 13,
                  color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toPrivacyWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        CommonWebPage.navigatorPush(context, PRIVACY_H5, "隐私协议");
      },
      child: Container(
        height: 50,
        alignment: Alignment.centerLeft,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Text(
              "隐私协议",
              style: TextStyle(
                  fontSize: 15,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7()
              ),
            ),
            Spacer(),
            Icon(
              Icons.arrow_forward_ios,
              size: 14,
              color: VgColors.INPUT_BG_COLOR,
            )
          ],
        ),
      ),
    );
  }

  Widget _toLogoutWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        bool result =
        await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示", content: "是否退出登录？");
        if (result == null || result == false) {
          return;
        }
        Future.delayed(Duration(milliseconds: 0), () async {
          await UserRepository.getInstance().clearUserInfo();
          RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,
              rootNavigator: false);
          VgToastUtils.toast(AppMain.context, "退出成功");
        });
      },
      child: Container(
        height: 50,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        alignment: Alignment.center,
        child: Text(
          "退出登录",
          style: TextStyle(
              fontSize: 15,
              color: ThemeRepository.getInstance().getMinorRedColor_F95355()
          ),
        ),
      ),
    );
  }
}
